package com.tuanzi.loan.web.bean.statistics.login;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.repository.common.impl.SecondaryChannelGroupRepository;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.request.statistics.login.StatCheckInRequest;
import com.tuanzi.loan.vo.response.channel.SecondaryChannelGroupResponse;
import com.tuanzi.loan.vo.response.statistics.login.StatCheckInResponse;
import com.tuanzi.loan.web.configuration.JSFListingBean;
import com.tuanzi.loan.web.lazy.statistics.login.StatCheckInLazyDataModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.Date;
import java.util.List;

import static com.tuanzi.loan.business.constants.DictionaryCode.CHANNEL_GROUP;
import static com.tuanzi.loan.business.constants.DictionaryCode.LARGE_COMMON_PRODUCT;

/**
 * @Author: chenweijun
 * @Date: 2019/3/14 11:17
 * @Description: 全局登记渠道统计
 */
@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class StatCheckInBean extends JSFListingBean<StatCheckInRequest, StatCheckInResponse> {

    private static final long serialVersionUID = 7978915770073434879L;

    @Autowired
    private SecondaryChannelGroupRepository secondaryChannelGroupRepository;

    private List<SecondaryChannelGroupResponse> secondaryChannelGroups;

    @PostConstruct
    private void init() {
        initLazyDataModel();
    }

    private void initLazyDataModel() {
        secondaryChannelGroups = secondaryChannelGroupRepository.findAll();
        $ = new StatCheckInRequest();
        $.setStartDate(new DateTime().minusDays(2).toDate());
        $.setEndDate(new Date());
        lazyDataModel = new StatCheckInLazyDataModel($);
    }

    public void onRest() {
        initLazyDataModel();
    }

    @Override
    protected List<String> getDictionaryCodes() {
        return Lists.newArrayList(CHANNEL_GROUP, LARGE_COMMON_PRODUCT);
    }

    public String translateSecondaryChannelGroup(Integer secondaryChannelGroupId) {
        return secondaryChannelGroupRepository.findNameById(secondaryChannelGroupId);
    }

    public void onChangeChannelGroup() {
        if ($.getChannelGroup() == null) {
            secondaryChannelGroups = secondaryChannelGroupRepository.findAll();
        } else {
            secondaryChannelGroups = secondaryChannelGroupRepository.findByPrimaryChannelGroup(Integer.valueOf($.getChannelGroup()));
        }
    }

    public List<SecondaryChannelGroupResponse> getSecondaryChannelGroups() {
        return secondaryChannelGroups;
    }
}
